﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using PmuRegistry.Silverlight.PmuRegistryDataServiceProxy; //   .PmuRegistryDataServiceProxy;
using PmuRegistry.Silverlight.Utilities;

namespace PmuRegistry.Silverlight.ModalDialogs
{
	public partial class Contacts : ChildWindow
	{
		int m_sourceCompanyID;
		string m_sourceCompanyAcronym;		
		PhasorDataServiceClient m_client;
		bool m_inEditMode = false;
		int m_contactID = 0;

		public Contacts(int companyID, string companyAcronym)
		{
			InitializeComponent();
			m_sourceCompanyID = companyID;
			m_sourceCompanyAcronym = companyAcronym;
			this.Title = "NASPI PMU Registry: Manage Contacts For " + m_sourceCompanyAcronym;			
			Loaded += new RoutedEventHandler(Contacts_Loaded);
			ButtonClear.Click += new RoutedEventHandler(ButtonClear_Click);
			ButtonSave.Click += new RoutedEventHandler(ButtonSave_Click);
			ListBoxContactList.SelectionChanged += new SelectionChangedEventHandler(ListBoxContactList_SelectionChanged);
			m_client = Common.GetPhasorDataServiceClient();
			m_client.GetContactListCompleted += new EventHandler<GetContactListCompletedEventArgs>(client_GetContactListCompleted);
			m_client.SaveContactCompleted += new EventHandler<SaveContactCompletedEventArgs>(client_SaveContactCompleted);
			m_client.GetContactTypesCompleted += new EventHandler<GetContactTypesCompletedEventArgs>(client_GetContactTypesCompleted);
		}

		void client_GetContactTypesCompleted(object sender, GetContactTypesCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxContactType.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Contact Types", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboboxContactType.Items.Count > 0)
				ComboboxContactType.SelectedIndex = 0;
		}

		void client_SaveContactCompleted(object sender, SaveContactCompletedEventArgs e)
		{
			SystemMessages sm;
			if (e.Error == null)
			{
				ClearForm();
				sm = new SystemMessages(new Message() { UserMessage = e.Result, SystemMessage = string.Empty, UserMessageType = MessageType.Success },
						ButtonType.OkOnly);
			}
			else
			{
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Save Contact Information", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
			}
			sm.Show();
			m_client.GetContactListAsync(m_sourceCompanyID);
		}

		void client_GetContactListCompleted(object sender, GetContactListCompletedEventArgs e)
		{
			if (e.Error == null)
				ListBoxContactList.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Contacts List", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
		}

		void ListBoxContactList_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (ListBoxContactList.SelectedIndex >= 0)
			{
				Contact selectedContact = ListBoxContactList.SelectedItem as Contact;
				GridContactDetail.DataContext = selectedContact;
				ComboboxContactType.SelectedItem = new KeyValuePair<int, string>(selectedContact.ContactTypeID, selectedContact.ContactTypeName);
				
				m_inEditMode = true;
				m_contactID = selectedContact.ID;
			}
		}

        void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            Storyboard sb = new Storyboard();
            sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
            sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
            Storyboard.SetTarget(sb, ButtonSaveTransform);
            sb.Begin();

            if (IsValid())
            {
                Contact contact = new Contact();
                contact.CompanyID = m_sourceCompanyID;
                contact.ContactTypeID = ((KeyValuePair<int, string>)ComboboxContactType.SelectedItem).Key;
                contact.FirstName = TextBoxFirstName.Text.CleanText();
                contact.LastName = TextBoxLastName.Text.CleanText();
                contact.Title = TextBoxTitle.Text.CleanText();
                contact.Email = TextBoxEmail.Text.CleanText();
                contact.Phone = TextBoxPhone.Text.CleanText();

                if (m_inEditMode == true && m_contactID > 0)
                {
                    contact.ID = m_contactID;
                    m_client.SaveContactAsync(contact, false);
                }
                else
                    m_client.SaveContactAsync(contact, true);
            }
        }

        bool IsValid()
        {
            bool isValid = true;

            if (string.IsNullOrEmpty(TextBoxFirstName.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid First Name", SystemMessage = "Please provide valid First Name.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxFirstName.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (string.IsNullOrEmpty(TextBoxLastName.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Last Name", SystemMessage = "Please provide valid Last Name.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxLastName.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (string.IsNullOrEmpty(TextBoxEmail.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Email Address", SystemMessage = "Please provide valid Email Address.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxEmail.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (string.IsNullOrEmpty(TextBoxPhone.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Phone Number", SystemMessage = "Please provide valid Phone Number", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxPhone.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            return isValid;
        }
        
		void ButtonClear_Click(object sender, RoutedEventArgs e)
		{
			Storyboard sb = new Storyboard();
			sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
			sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
			Storyboard.SetTarget(sb, ButtonClearTransform);
			sb.Begin();
			ClearForm();	
		}

		void Contacts_Loaded(object sender, RoutedEventArgs e)
		{
			m_client.GetContactTypesAsync();
			m_client.GetContactListAsync(m_sourceCompanyID);
		}

		void ClearForm()
		{
			GridContactDetail.DataContext = new Contact();
			ComboboxContactType.SelectedIndex = 0;
			ListBoxContactList.SelectedIndex = -1;

			m_inEditMode = false;
			m_contactID = 0;
		}
				
	}
}

